<template>
  <div class="tabs-container">
    <el-tabs 
      v-model="activeTab" 
      type="card" 
      class="dynamic-tabs"
      @tab-remove="removeTab"
      @tab-click="clickTab"
    >
      <el-tab-pane
        v-for="item in visitedViews"
        :key="item.path"
        :label="item.title"
        :name="item.path"
        :closable="item.path !== '/back/dashboard'"
      >
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '@/store/app'

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()

// 活动标签
const activeTab = ref('/back/dashboard')

// 访问的视图列表
const visitedViews = computed(() => appStore.visitedViews)

// 添加访问的视图
const addVisitedView = (view) => {
  appStore.addVisitedView({
    path: view.path,
    title: view.meta.title || '未命名页面',
    name: view.name
  })
}

// 监听路由变化，添加标签
watch(
  () => route.path,
  (val) => {
    addVisitedView(route)
    activeTab.value = val
  },
  { immediate: true }
)

// 移除标签
const removeTab = (targetPath) => {
  appStore.removeVisitedView(targetPath)
  
  // 如果关闭的是当前激活的标签，则需要跳转到其他标签
  if (activeTab.value === targetPath) {
    toLastView(targetPath)
  }
}

// 跳转到最后一个标签
const toLastView = (targetPath) => {
  const latestView = visitedViews.value.slice(-1)[0]
  
  if (latestView) {
    router.push(latestView.path)
  } else {
    // 如果没有标签了，跳转到仪表盘页面
    router.push('/back/dashboard')
  }
}

// 点击标签
const clickTab = (tab) => {
  router.push(tab.props.name)
}

// 组件挂载时，添加当前路由到标签
onMounted(() => {
  addVisitedView(route)
})
</script>

<style lang="scss" scoped>
.tabs-container {
  padding: 0 16px;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  
  .dynamic-tabs {
    :deep(.el-tabs__header) {
      margin-bottom: 0;
      border-bottom: none;
      
      .el-tabs__item {
        height: 36px;
        line-height: 36px;
        border: 1px solid #dcdfe6;
        border-bottom: none;
        
        &.is-active {
          background-color: #f0f6ff;
          color: #409eff;
          border-bottom: none;
        }
        
        &:hover {
          color: #409eff;
        }
        
        .el-icon-close {
          font-size: 12px;
          
          &:hover {
            background-color: #ff4d51;
            color: #fff;
          }
        }
      }
    }
    
    :deep(.el-tabs__content) {
      display: none; // 不显示内容区域，因为内容通过router-view显示
    }
  }
}
</style> 